#pragma once

#include "Socket.hpp"
#include "Connection.hpp"
#include "IoService.hpp" 
#include "Calculator.hpp"
using namespace SocketModule;
class Listener : public Connection
{
public:
    Listener(uint16_t port)
        : _port(port)
    {
        _listen_socket = std::make_shared<Tcpsocket>();
        _listen_socket->BuildTcpserver(_port);
        SetConnectionFd(_listen_socket->FD());
        Setevents(EPOLLIN | EPOLLET);
    }

    void Reader() override
    {
        InetAddr peer;
        int aerrno = 0;
        //谁说只能有一个连接到来的??
        while(true)
        {
            int socketfd = _listen_socket->accpetor(&peer,&aerrno);
            if (socketfd > 0)
            {
                LOG(LogLevel::INFO) << "get a new fd: " << socketfd;
                // 构建connection，连入到epoll中
                auto conn = std::make_shared<IoService>(socketfd);
                conn->SetPeerInfo(peer);
                //把处理完整性函数注册进去
                conn->RegisterHandler(HandlerRequest);
                //添加到epoll模型当中
                GetOwner()->InsertConnection(conn);
            }
            
            else 
            {
                if (aerrno == EAGAIN || aerrno == EWOULDBLOCK)
                {
                    LOG(LogLevel::INFO) << "accept all fd done...";
                    break;
                }
                else if(aerrno == EINTR)
                {
                    LOG(LogLevel::INFO) << "被信号中断，继续读";
                    continue;
                }
                else 
                {
                    LOG(LogLevel::WARNING) << "accept error ... Ignore";
                    break;
                }
            }
        }
       
    }
    int Fd()
    {
        return _listen_socket->FD();
    }
    ~Listener() override {}

private:
    uint16_t _port;
    std::shared_ptr<Socket> _listen_socket;
};